package wili.attrMapping._user.b1.exp;

import java.util.Map;
import java.util.function.Predicate;

import wili.c.Ca;
import wili.c.Str9a;
import wili.c.reg.MatchRet;

/**
 * 
 * @author weila 2022年10月5日
 */
public class Varb1 extends VarOrValueb1 {
	public String toString() {
		return this.getString(1);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T value() {
		Object ret = this.strValue;
		if (ret == null)
			return null;
		String st = ret.toString();
		if (st.equals("true"))
			return (T) Boolean.valueOf(this.isNot);
		if (st.equals("false") || st.equals("undefined") || st.equals("null"))
			return (T) Boolean.valueOf(!this.isNot);
		return (T) ret;
	}

	public Varb1(MatchRet mat) {
		this.expSt = mat.s0.substring(mat.from, mat.to);
		if (mat.sons == null) {
			String st = mat.getString(1);
			Ca.asert(st.matches("!*#.+"), st);
			this.name = st;
			return;
		} else {
			String st0 = mat.son(0).getString(1);
			Ca.asert(st0.matches("^!*[\\$@]?\\{"), st0);
			int len = Str9a.readChars('!', st0, 0).length();
			if (len > 0) {// eg. !!name 在js中有特别用途: 转boolean.
				this.isNot = len % 2 == 1;
			}
		}
		MatchRet nod = mat.son(1);
		String st2 = nod.getString(1);
		String[] tt = st2.split("/");
		this.name = tt[tt.length - 1];
	}

	public void traverse(Predicate<MathExpB1> pred) {
		pred.test(this);
	}

	public boolean equals(Object o) {
		if (o instanceof Varb1) {
			Varb1 obj = (Varb1) o;
			if ((obj).name.equals(this.name)) {
				if (obj.isNot == this.isNot)
					return true;
			}
		}
		return false;
	}

	@Override
	public Boolean isTrue() {
		return (Boolean) value();
	}

	public void setValue(Map<String, Object> map) {
		Object va = map.get(this.name);
		this.strValue = va.toString();
	}

	public String getString(int refresh) {
		return this.expSt;
	}
}
